package com.logos;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;

public class XMLParser {
    public static void main(String[] args) {
        try {
            // 创建一个DocumentBuilderFactory对象
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            // 创建一个DocumentBuilder对象
            DocumentBuilder builder = factory.newDocumentBuilder();
            // 解析XML文件
            Document document = builder.parse(new File("C:\\学习\\java\\study-technology\\study-javaSE\\src\\test\\resources\\test.xml"));
            // 规范化文档
            document.getDocumentElement().normalize();
            // 获取根元素
            Element root = document.getDocumentElement();
            // 获取所有person元素
            NodeList personList = root.getElementsByTagName("person");
            // 遍历person元素
            for (int i = 0; i < personList.getLength(); i++) {
                Node person = personList.item(i);
                if (person.getNodeType() == Node.ELEMENT_NODE) {
                    Element personElement = (Element) person;
                    // 获取name、age和city元素
                    String name = personElement.getElementsByTagName("name").item(0).getTextContent();
                    String age = personElement.getElementsByTagName("age").item(0).getTextContent();
                    String city = personElement.getElementsByTagName("city").item(0).getTextContent();
                    // 打印信息
                    System.out.println("Name: " + name);
                    System.out.println("Age: " + age);
                    System.out.println("City: " + city);
                    System.out.println("----------------------");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
